﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcWeb.Controllers
{
    public class DeptController : BaseController
    {
        // GET: /Dept/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Edit(int id)
        {
            var model = db.User_Depts.Find(id);
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult Edit(int? id, EAM.Model.User_Dept viewModel)
        {
            if (id == null)
            {
                viewModel.ParentId = viewModel.ParentId ?? 0;
                viewModel.OrderIndex = viewModel.OrderIndex ?? 0;
                db.User_Depts.Add(viewModel);
            }
            else
            {
                var model = db.User_Depts.Find(id);
                UpdateModel(model);
            }

            bool flag = true;
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                flag = false;
            }

            return Json(flag);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            var model = db.User_Depts.Find(id);
            db.User_Depts.Remove(model);
            db.SaveChanges();

            return Json(true);
        }

        public ActionResult Root()
        {
            var allNodeList = db.User_Depts.ToList();
            List<DeptNode> deptList = new List<DeptNode>();
            DeptNode node = new DeptNode { id = 0, text = "广西人才市场" };
            deptList.Add(node); //虽然奇怪，但是ligerui认不出不带[]的json，所以只好多加到list
            SetTreeNode(allNodeList, node);

            return Json(deptList, JsonRequestBehavior.AllowGet);
        }

        [NonAction]
        void SetTreeNode(List<EAM.Model.User_Dept> allNodeList, DeptNode node)
        {
            var list = allNodeList.Where(m => m.ParentId == node.id).OrderBy(m => m.OrderIndex).ToList();
            if (list.Count > 0)
            {
                node.children = new List<DeptNode>();
                DeptNode child = null;
                foreach (var m in list)
                {
                    child = new DeptNode { id = m.Id, text = m.Name };
                    node.children.Add(child);
                    SetTreeNode(allNodeList, child);
                }
            }
        }
    }

    //部门列表，嵌套
    public class DeptNode
    {
        public int id { get; set; }
        public string text { get; set; }
        public List<DeptNode> children { get; set; }
    }
}
